package org.ccay.manage.log.service.impl;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.Audit;
import org.ccay.log.LoggerInfoVO;
import org.ccay.log.webtrace.impl.LogLevelSwitcher;
import org.ccay.log.webtrace.impl.WebTraceStatusManager;
import org.ccay.manage.log.service.ILogLevelService;
import org.ccay.ws.service.IClusterInvokeService;

/**
 * 动态调整调试日志级别服务的实现
 * 
 * @author chaowangbang
 * @since 2012-4-25
 */
@Named("logLevelService")
public class LogLevelService implements ILogLevelService {

	@Inject
	private IClusterInvokeService cluster;
	/**
	 * 日志级别列表
	 */
	public List<LoggerInfoVO> findAllLoggers() {
		// 获取所有logger
		List<LoggerInfoVO> allLogger = LogLevelSwitcher.getInstance().findAllLoggers();
		return allLogger;

	}
	

	/**
	 * 查询单个Logger
	 */
	public LoggerInfoVO findLogger(LoggerInfoVO logger){
		LoggerInfoVO targetLogger = LogLevelSwitcher.getInstance().fingLogger(logger.getLoggerName());
		if(targetLogger != null){
			targetLogger.setTraceUserAccount(WebTraceStatusManager.getInstance().getUserAccount2Trace());
		}
		return targetLogger;
	}
	
	/**
	 * 修改日志级别,向集群服务发送请求
	 * @param logger
	 * @throws ApplicationException
	 */
	@Audit(module="Web Trace Management",operation="Web Trace",message="update web Trace:{loggerName},{level},{traceUserAccount}")
	public void updateClusterLogLevel(LoggerInfoVO logger)
			throws ApplicationException{
		String uri = "services/ccay/logs/logLevel/single/{0}/{1}/{2}/{3}";
		uri = MessageFormat.format(uri,logger.getLoggerName(),logger.getLevel(),logger.getTime(),logger.getTraceUserAccount());
		cluster.invoke(uri, "");
	}
	
	/**
	 * 修改并保存日志级别，集群内部调用
	 * @param logger
	 * @throws ApplicationException
	 */
	public void switchLogLevel(LoggerInfoVO logger)
			throws ApplicationException {
		//执行修改
		LogLevelSwitcher.getInstance().switchLevel(logger);
	}


	/* (non-Javadoc)
	 * @see org.ccay.log.service.ILogLevelService#findWebTraceInfo()
	 */
	public Map<String, String> findWebTraceInfo() {
		Map<String,String> info = new HashMap<String,String>();
		
		info.put("webTraceEnabled", String.valueOf(WebTraceStatusManager.isWebTraceEnabled));
		info.put("userAccount2Trace", WebTraceStatusManager.getInstance().getUserAccount2Trace());
		
		return info;
	}
}
